package com.xdh.zzqh.ui.view

import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.xdh.zzqh.R
import com.xdh.zzqh.utils.dimenById


fun showViews(
    parent: View,
    items: List<String>,
    onSelect: (Int, String) -> Unit//选中返回
//    onClose: () -> Unit//关闭显示
) {
    val view = LayoutInflater.from(parent.context).inflate(R.layout.spinner_window, null)
    val recyclerView = view.findViewById<RecyclerView>(R.id.id_csw_rv)

    val window = PopupWindow(
        view,
        dimenById(R.dimen.popup_width),
        dimenById(R.dimen.popup_height),
        true
    )

    recyclerView.layoutManager =
        FlexboxLayoutManager(parent.context, FlexDirection.ROW, FlexWrap.WRAP)
    recyclerView.adapter = SpinnerAdapter(items) { index, item ->
        onSelect(index, item)
        window.dismiss()
    }
    window.animationStyle = R.style.PopupTheme
    window.isOutsideTouchable = true
//    window.setOnDismissListener { onClose() }
    window.showAtLocation(parent, Gravity.CENTER, 0, 0)
}

class SpinnerAdapter(val items: List<String>, val cb: (Int, String) -> Unit) :
    RecyclerView.Adapter<SpinnerItem>() {
    override fun onBindViewHolder(holder: SpinnerItem, position: Int) {
        holder.setUp(position, items[position], cb)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SpinnerItem {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_custom_sp, parent, false)
        return SpinnerItem(view)
    }

    override fun getItemCount(): Int {
        return items.size
    }
}

class SpinnerItem(itemView: View) : RecyclerView.ViewHolder(itemView) {
    private val tv = itemView.findViewById<TextView>(R.id.id_item_custom_sp_tv)
    fun setUp(index: Int, item: String, cb: (Int, String) -> Unit) {
        tv.text = item
        tv.setOnClickListener { cb(index, item) }
    }
}
